﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Data.Objects;
using System.Data.Objects.DataClasses;
using TrucksDir.Data;
using System.Data;

namespace TrucksDir.Data.Services
{
 public class BaseDAO<TEntity> where TEntity : EntityObject//, IEntityWithRelationships
 {
  public static EntityObject Get(EntityKey key)
  {
   return (TEntity) Context.Instance.GetObjectByKey(key);
  }

  public static EntityObject GetObjectByID(object id)
  {
      Type t = typeof(TEntity);
      ObjectSet<TEntity> list = Context.Instance.CreateObjectSet<TEntity>(t.Name);

      foreach (TEntity entidad in list)
      {
          //Si no lo convertimos a string, no compara correctamente los valores numéricos
          object id_ = entidad.EntityKey.EntityKeyValues[0].Value.ToString();
          if (id_.Equals(id)) return entidad;
      }
      return null;
  }

  public static ObjectSet<TEntity> GetList()
  {
   return Context.Instance.CreateObjectSet<TEntity>();
  }

  public static void InsertOnSubmit(TEntity entity)
  {
   Context.Instance.AddObject(entity.GetEntitySetName(), entity);
  }

  public static void DeleteOnSubmit(TEntity entity)
  {
   Context.Instance.DeleteObject(entity);
  }
 }
}
